package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
import model.Configuration;
import entities.Mesa;
import entities.QueryResult;
import filters.AndFilter;
import filters.IFilter;
import filters.SexFilter;

public class MySQLDatabase implements IStorage {

	Connection conn = null;

	public MySQLDatabase() throws ClassNotFoundException {

		try {
			Class.forName("com.mysql.jdbc.Driver");

			System.out.println("Trying to conect to dbase");
			conn = DriverManager.getConnection(
					Configuration.Storage.Database.ConnectionString,
					Configuration.Storage.Database.Username,
					Configuration.Storage.Database.Password);

			System.out.println("Database connection established");
		} catch (SQLException ex) {
			System.out.println(ex);
		}
	}

	@Override
	public boolean store(Mesa m) {
		// Agregamos la mesa
		try {
			String stat = "INSERT INTO `grupo7`.`mesa` (`Nro_mesa`, `Sexo`, `Barrio`) VALUES ('"
					+ m.getNroMesa()
					+ "','"
					+ m.getSexo()
					+ "','"
					+ m.getBarrio() + "');";
			PreparedStatement query = (PreparedStatement) conn.prepareStatement(stat);
			query.execute();
		} catch (SQLException e) {
			System.out.println("Error al cargar la mesa");
			return false;
		}

		// Agregamos los votos
		try {

			Enumeration<String> ptdos = m.getPartidos();
			while (ptdos.hasMoreElements()) {
				String ptdo = ptdos.nextElement();
				String stat = "INSERT INTO `grupo7`.`votos` (`Nro_mesa`, `Partido`, `Cantidad`) VALUES ('"
						+ m.getNroMesa()
						+ "', '"
						+ ptdo
						+ "', '"
						+ m.getCantVotos(ptdo) + "');";
				PreparedStatement query = (PreparedStatement) conn.prepareStatement(stat);
				query.execute();
			}

		} catch (SQLException e) {
			System.out.println("Error al cargar los votos");
			return false;
		}
		return true;
	}
	
	public QueryResult query(IFilter filter){
		try{
			String qString = "SELECT v.Partido,SUM(v.Cantidad) FROM mesa m, votos v WHERE (m.Nro_mesa = v.Nro_mesa AND ("+filter.getQuery()+")) GROUP BY v.Partido;";
			PreparedStatement query = (PreparedStatement) conn.prepareStatement(qString);
			ResultSet result = query.executeQuery();	
			QueryResult qResult = new QueryResult();			
			Integer total = 0;
			while(result.next()){
				total+=result.getInt(2);
				qResult.addVoto(result.getString(1), result.getInt(2));
			}			
			//Agrego total de votos
			qResult.setTotal(total);			
			//Agregar ptjes
			Enumeration<String> ptdos = qResult.getPartidos();
			while (ptdos.hasMoreElements()) {
				String ptdo = ptdos.nextElement();
				qResult.addPtjeVoto(ptdo, qResult.getCantVotos(ptdo));
			}			
			return qResult;
		}catch (Exception e){
			System.out.println("Error al hacer la consulta");
			return null;
		}
	}
}
